package com.heima.user.service.impl;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.behavior.dto.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dto.UserRelationDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserFan;
import com.heima.model.user.pojo.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    /**
     * 关注或取消关注
     * @param dto
     * @return
     */

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ApUserMapper apUserMapper;

    //涉及多表  需要加事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //检查参数(作者id    操作行为  0  关注和   1 取消关注)
       if (dto.getAuthorId()==null){
           throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"作者id不能为空");
       }
       if (dto.getOperation()==null||(dto.getOperation()!=1&&dto.getOperation()!=0)){//并且
           throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"操作状态错误");
       }
       //远程调用作者(author)对应的user信息
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());
        if (apAuthor==null){
           throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
       }

        ApUser followUser = apUserMapper.selectById(apAuthor.getUserId());//apuser  一个作者  一个用户  得到用户信息
        if (followUser==null){//被关注的用户
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"作者用户信息不存在");
        }

        //获取当前登录的用户
        ApUser loginUser = AppThreadLocalUtils.getUser();
        if (loginUser==null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //不可以关注自己
        if (followUser.getId().equals(loginUser.getId())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"不可以关注自己");
        }
        //如果操作行为是0,关注作者
        if (dto.getOperation()==0){
            return followByUserId(loginUser,followUser,dto.getArticleId());
        }else {
            //如果操作行为是1,取消关注作者
            return followCancelByUserId(loginUser,followUser);
        }

    }
    @Autowired
    ApUserFanMapper apUserFanMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;//对应数据库的表    实体类来接收     mapper   对应   mysql

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;


    //取消关注
    private ResponseResult followCancelByUserId(ApUser loginUser, ApUser followUser) {
        //删除两张表的相关的消息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, loginUser.getId()).eq(ApUserFollow::getFollowId, followUser.getId()));
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId,followUser.getId()).eq(ApUserFan::getFansId,loginUser.getId()));

        return ResponseResult.okResult();
    }

    //添加关注
    private ResponseResult followByUserId(ApUser loginUser, ApUser followUser, Long articleId) {
        //先到关注表查
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, loginUser.getId()).eq(ApUserFollow::getFollowId, followUser.getId()));

        if (apUserFollow!=null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"已经关注过该用户");
        }

        //创建关注信息,保存
        apUserFollow = new ApUserFollow();//新建对象
        apUserFollow.setUserId(loginUser.getId());
        apUserFollow.setFollowId(followUser.getId());
        apUserFollow.setFollowName(followUser.getName());
        apUserFollow.setLevel((short)0);
        apUserFollow.setIsNotice(false);
        apUserFollow.setCreatedTime(new Date());

        apUserFollowMapper.insert(apUserFollow);

        //创建粉丝信息,保存
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followUser.getId()).eq(ApUserFan::getFansId, loginUser.getId()));

        if (apUserFan==null){
            apUserFan = new ApUserFan();
            apUserFan.setUserId(followUser.getId());
            apUserFan.setFansId(Long.valueOf(loginUser.getId()));
            //loginUser 中  没有 name
            ApUser apUser = apUserMapper.selectById(loginUser.getId());
            apUserFan.setFansName(apUser.getName());
            apUserFan.setLevel((short)0);
            apUserFan.setCreatedTime(new Date());
            apUserFan.setIsDisplay(false);
            apUserFan.setIsShieldLetter(false);
            apUserFan.setIsShieldComment(false);

            apUserFanMapper.insert(apUserFan);
        }

        //发送消息   封装了dto
        //创建对象
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setArticleId(articleId);
        followBehaviorDto.setFollowId(followUser.getId());
        followBehaviorDto.setUserId(loginUser.getId());


        //添加关注成功后发送消息   关注行为
        //关注后,要保存关注行为
        //使用mq将关注行为发送到行为微服务中
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));//序列化采用的是字符串

        return ResponseResult.okResult();



    }
}
